const hre = require("hardhat");
const { ethers } = hre;
const fs = require('fs');

async function main() {
  console.log("🚀 开始部署和测试图书NFT系统...\n");

  // 获取部署账户
  const [deployer, buyer] = await ethers.getSigners();
  console.log("📋 账户信息:");
  console.log("  部署者地址:", deployer.address);
  console.log("  买家地址:", buyer.address);
  console.log("  部署者余额:", ethers.utils.formatEther(await deployer.getBalance()), "ETH");
  console.log("  买家余额:", ethers.utils.formatEther(await buyer.getBalance()), "ETH\n");

  console.log("=".repeat(60));
  console.log("📦 第一阶段：部署合约");
  console.log("=".repeat(60));

  try {
    // 1. 部署 TraceBook 合约
    console.log("1️⃣ 部署 TraceBook 合约...");
    const TraceBook = await ethers.getContractFactory("TraceBook");
    const traceBook = await TraceBook.deploy();
    await traceBook.deployed();
    console.log("✅ TraceBook 部署成功:", traceBook.address);

    // 2. 部署 BookIPFSManager 合约
    console.log("2️⃣ 部署 BookIPFSManager 合约...");
    const BookIPFSManager = await hre.ethers.getContractFactory("BookIPFSManager");
    const ipfsManager = await BookIPFSManager.deploy();
    await ipfsManager.deployed();
    console.log("✅ BookIPFSManager 部署成功:", ipfsManager.address);

    // 3. 部署 BOOK1155 合约
    console.log("3️⃣ 部署 BOOK1155 合约...");
    const BOOK1155 = await hre.ethers.getContractFactory("BOOK1155");
    const book1155 = await BOOK1155.deploy(traceBook.address);
    await book1155.deployed();
    console.log("✅ BOOK1155 部署成功:", book1155.address);

    // 4. 部署 TokenMarketplace 合约
    console.log("4️⃣ 部署 TokenMarketplace 合约...");
    const TokenMarketplace = await hre.ethers.getContractFactory("TokenMarketplace");
    const marketplace = await TokenMarketplace.deploy(traceBook.address);
    await marketplace.deployed();
    console.log("✅ TokenMarketplace 部署成功:", marketplace.address);

    // 5. 设置合约关联
    console.log("5️⃣ 设置合约关联...");
    await book1155.setIPFSManagerContract(ipfsManager.address);
    await traceBook.setApprovalForAll(book1155.address, true);
    await traceBook.setApprovalForAll(marketplace.address, true);
    console.log("✅ 合约关联设置完成\n");

    console.log("=".repeat(60));
    console.log("🧪 第二阶段：测试功能");
    console.log("=".repeat(60));

    // 测试数据
    const testBook = {
      id: 1,
      ISBN: "978-0123456789",
      amount: 10,
      imageURI: "https://example.com/book-cover.jpg",
      price: hre.ethers.utils.parseEther("0.1"), // 0.1 ETH
      contentHash: "QmTestContentHash123456789",
      metadataHash: "QmTestMetadataHash123456789",
      previewHash: "QmTestPreviewHash123456789",
      isEncrypted: false,
      encryptionKey: ""
    };

    // 1. 铸造图书代币
    console.log("1️⃣ 铸造图书代币...");
    console.log(`   📖 图书信息: ${testBook.ISBN}`);
    console.log(`   🔢 铸造数量: ${testBook.amount}`);
    console.log(`   💰 价格: ${hre.ethers.utils.formatEther(testBook.price)} ETH`);
    
    const mintTx = await book1155.mint(
      testBook.id,
      testBook.ISBN,
      testBook.amount,
      testBook.imageURI,
      testBook.price,
      testBook.contentHash,
      testBook.metadataHash,
      testBook.previewHash,
      testBook.isEncrypted,
      testBook.encryptionKey
    );
    await mintTx.wait();
    
    const balance = await book1155.balanceOf(deployer.address, testBook.id);
    console.log("✅ 图书代币铸造成功！");
    console.log(`   📚 部署者拥有的代币数量: ${balance.toString()}`);

    // 2. 查看IPFS内容
    console.log("\n2️⃣ 查看IPFS内容信息...");
    const ipfsContent = await ipfsManager.getBookIPFSContent(testBook.ISBN);
    console.log("✅ IPFS内容信息:");
    console.log(`   📄 内容哈希: ${ipfsContent[0]}`);
    console.log(`   📋 元数据哈希: ${ipfsContent[1]}`);
    console.log(`   👁️ 预览哈希: ${ipfsContent[2]}`);
    console.log(`   🕒 上传时间: ${new Date(Number(ipfsContent[3]) * 1000).toLocaleString()}`);

    // 3. 设置市场授权并上架
    console.log("\n3️⃣ 上架图书到市场...");
    await book1155.setApprovalForAll(marketplace.address, true);
    
    const listingTx = await marketplace.createListing(
      book1155.address,
      testBook.id,
      5 // 上架5本
    );
    await listingTx.wait();
    console.log("✅ 图书上架成功！");

    // 查看上架信息
    const activeListings = await marketplace.getAllActiveListings();
    console.log("📋 当前上架的图书:");
    for (let i = 0; i < activeListings.length; i++) {
      const listing = activeListings[i];
      console.log(`   📖 ISBN: ${listing.ISBN}`);
      console.log(`   🔢 可购买数量: ${listing.amount}`);
      console.log(`   💰 单价: ${hre.ethers.utils.formatEther(listing.price)} ETH`);
    }

    // 4. 买家购买图书
    console.log("\n4️⃣ 买家购买图书...");
    const purchaseAmount = 2;
    const totalPrice = testBook.price.mul(purchaseAmount);
    
    console.log(`   🛒 购买数量: ${purchaseAmount}`);
    console.log(`   💳 总价: ${hre.ethers.utils.formatEther(totalPrice)} ETH`);
    
    const purchaseTx = await marketplace.connect(buyer).executePurchase(
      0, // listingId
      purchaseAmount,
      { value: totalPrice }
    );
    await purchaseTx.wait();
    
    const buyerBalance = await book1155.balanceOf(buyer.address, testBook.id);
    console.log("✅ 购买成功！");
    console.log(`   📚 买家拥有的代币数量: ${buyerBalance.toString()}`);

    // 5. 查看买家拥有的图书
    console.log("\n5️⃣ 查看买家拥有的图书...");
    const ownedBooks = await marketplace.getOwnInformation(buyer.address);
    console.log("✅ 买家拥有的图书代码:");
    ownedBooks.forEach((tokenCode, index) => {
      console.log(`   ${index + 1}. ${tokenCode}`);
    });

    // 6. 查看追溯信息
    console.log("\n6️⃣ 查看图书追溯信息...");
    if (ownedBooks.length > 0) {
      const traceInfo = await traceBook.traceBook(ownedBooks[0]);
      console.log("✅ 追溯信息 (JSON格式):");
      console.log(traceInfo);
    }

    console.log("\n" + "=".repeat(60));
    console.log("🎉 所有测试完成！系统运行正常！");
    console.log("=".repeat(60));

    // 保存合约地址
    const addresses = {
      TraceBook: traceBook.address,
      BookIPFSManager: ipfsManager.address,
      BOOK1155: book1155.address,
      TokenMarketplace: marketplace.address,
      deployer: deployer.address,
      buyer: buyer.address
    };

    fs.writeFileSync('deployed-addresses.json', JSON.stringify(addresses, null, 2));
    console.log("📄 合约地址已保存到 deployed-addresses.json");

    console.log("\n📊 最终状态总结:");
    console.log(`   📚 总铸造代币: ${testBook.amount}`);
    console.log(`   🏪 已上架数量: 5`);
    console.log(`   🛒 已售出数量: ${purchaseAmount}`);
    console.log(`   💰 剩余可购买: ${5 - purchaseAmount}`);
    console.log(`   👤 买家拥有: ${buyerBalance.toString()}`);

    console.log("\n🔍 如何判断铸币是否成功:");
    console.log("   ✅ 看到 '图书代币铸造成功！' 消息");
    console.log("   ✅ 部署者拥有的代币数量显示为 10");
    console.log("   ✅ IPFS内容信息正确显示");
    console.log("   ✅ 图书成功上架到市场");
    console.log("   ✅ 买家成功购买并拥有代币");
    console.log("   ✅ 追溯信息正确记录");

  } catch (error) {
    console.error("❌ 执行过程中出现错误:");
    console.error("错误信息:", error.message);
    if (error.reason) {
      console.error("错误原因:", error.reason);
    }
    if (error.transaction) {
      console.error("交易哈希:", error.transaction.hash);
    }
    console.log("\n🔍 常见错误解决方案:");
    console.log("   1. 编译错误: 运行 npx hardhat clean && npx hardhat compile");
    console.log("   2. 网络错误: 检查网络连接");
    console.log("   3. 权限错误: 检查合约授权设置");
    process.exit(1);
  }
}

main()
  .then(() => {
    console.log("\n✨ 程序执行完成！");
    process.exit(0);
  })
  .catch((error) => {
    console.error("❌ 程序执行失败:", error);
    process.exit(1);
  }); 